using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace csammisrun.MsnLib
{
  public static class Logging
  {
    private static StreamWriter _streamwriter = null;
    private static bool _console = false;

    public static void WriteString(string message)
    {
      if (_streamwriter != null)
      {
        _streamwriter.WriteLine(DateTime.Now.ToString() + " - " + message);
        _streamwriter.Flush();
      }
      if (_console)
      {
        Console.WriteLine(message);
      }
    }

    public static void Init(string filename)
    {
      try
      {
        _streamwriter = new StreamWriter(filename, false);
      }
      catch(Exception ex)
      {
        Console.WriteLine("Could not start file logging, defaulting to console logging");
        _streamwriter = null;
        _console = true;
      }
    }

    public static bool EchoToConsole
    {
      get { return _console; }
      set { _console = value; }
    }

    public static void LogMessageReceived(Message msg, int _id)
    {
      string log = String.Format("Message received on switchboard {0}:\r\n" +
        "\tContent-Type: {1}\r\n" +
        "\tFrom: {2}", _id, msg.ContentType, msg.RemoteUser);

      if (Encoding.UTF8.GetString(msg.Body).Trim() != "")
      {
        log += String.Format("\r\n" +
        "\t------------ Message Start ------------\r\n" +
        "{0}\r\n" +
        "\t------------ Message End --------------", Encoding.UTF8.GetString(msg.Body));
      }
      WriteString(log);
    }

    public static void LogMessageSent(Message msg, int _id)
    {
      string log = String.Format("Message sent on switchboard {0}:\r\n" +
        "\tContent-Type: {1}\r\n" +
        "\t------------ Message Start ------------\r\n" +
        "{2}\r\n" +
        "\t------------ Message End --------------", _id, msg.ContentType, Encoding.UTF8.GetString(msg.Body));
      WriteString(log);
    }
  }
}
